import Vue from 'vue';
import VueI18n from 'vue-i18n';
import { getUrlParams, unique } from './utils';

Vue.use(VueI18n);

export const i18n = new VueI18n({
  locale: 'zh_cn', // 设置语言 
  fallbackLocale: ['en', 'zh_cn'], // 按顺序加载备选文案
  // 语言包
  messages: {}
});

export default VueI18n;

/**
 * 加载语言包
 */
function loadLanguages() {
  let { language } = getUrlParams();
  if (!language) {
    language = 'zh_cn';
  }
  const locale = language.toLowerCase();
  i18n.locale = locale;

  const languages = unique([locale, 'en', 'zh_cn']);
  const locales = require.context('@/languages', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      if (languages.includes(locale)) {
        i18n.setLocaleMessage(locale, locales(key));
      }
    }
  });
}

loadLanguages();
